import Taro, { redirectTo, showToast, removeStorageSync } from '@tarojs/taro';
import { CacheAppStartRouter, CacheCookies } from '../constant/cache';
import { proxy } from '../constant/config';
import { getCache } from './utils';

const request = ({ url = '', method = 'GET', data = {}, header = {} }) => {
  console.log('request', url);
  return new Promise((resolve, reject) => {
    Taro.request({
      url: proxy + url,
      data,
      header: {
        'Content-Type': 'application/json',
        cookie: getCache(CacheCookies),
        ...header
      },
      credentials: 'include',
      method: method.toUpperCase()
    })
      .then((res) => {
        const { statusCode, data } = res;
        if (statusCode >= 200 && statusCode < 300) {
          if (typeof data === 'string' && data.includes('user-login')) {
            const router = getCache(CacheAppStartRouter, true);
            const {
              params: { path, query = {} }
            } = router || { params: { path: '' } };
            const ref = path
              ? '/' +
                path +
                '?' +
                Object.keys(query)
                  .map((x) => x + '=' + query[x])
                  .join('&')
              : '';
            redirectTo({ url: '/pages/auth/login?ref=' + encodeURIComponent(ref) });
            resolve({ status: -1, data: '', message: '需要登录' });
            return;
          } else {
            removeStorageSync(CacheAppStartRouter);
            if (typeof data['data'] === 'string') {
              data.data = JSON.parse(data.data);
              resolve(data);
            } else {
              resolve(data);
            }
          }
        } else {
          throw new Error(`网络请求错误，状态码${statusCode}`);
        }
      })
      .catch((error) => {
        console.error(error);
        showToast({ title: error.message, icon: 'none' });
        resolve({ status: 0, data: '', message: error.message });
      });
  });
};

export default request;
